package com.kaisheng.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaisheng.entity.Infos;
import com.kaisheng.entity.Project;
import com.kaisheng.entity.User;
import com.kaisheng.util.DBHelp;
import com.kaisheng.util.RowMapper;

public class InfosDao {

	DBHelp<Infos> db = new DBHelp<Infos>();
	public boolean save(Infos info) {
		String sql = "INSERT INTO t_info(id,user_id,project_id,mess,createtime) VALUES (?,?,?,?,?)";
		return db.executeSQL(sql, info.getId(),info.getUser_id(),info.getProject_id(),info.getMessage(),info.getCreatetime());
		
	}

	public List<Infos> findAll(String project_id) {
		StringBuilder sql = new StringBuilder();
		sql.append(" SELECT in.id,in.user_id ,u.name AS username,u.password,u.email,u.pic ,in.project_id, p.name AS projectname,p.describe,p.createtime AS projectcreatetime,in.mess,in.createtime AS infoscreatetime FROM t_info AS `in` ");
		sql.append(" LEFT JOIN t_project AS p ON in.project_id = p.id  ");
		sql.append(" LEFT JOIN t_user AS u ON in.user_id = u.id  ");
		sql.append(" WHERE in.project_id =  ? ORDER BY in.createtime DESC ");
		return db.executeQueryForList(sql.toString(), new InfosRowMapper(), project_id);
	}
	
	private class InfosRowMapper implements RowMapper<Infos> {

		public Infos mapRow(ResultSet rs) throws SQLException {
			Infos in = new Infos();
			in.setId(rs.getString("id"));
			in.setMessage(rs.getString("mess"));
			in.setCreatetime(rs.getString("infoscreatetime"));
			
			User u = new User();
			u.setId(rs.getString("user_id"));
			u.setName(rs.getString("username"));
			u.setPassword(rs.getString("password"));
			u.setEmail(rs.getString("email"));
			u.setPic(rs.getString("pic"));
			
			in.setUser(u);
			in.setUser_id(rs.getString("user_id"));
			
			Project p = new Project();
			p.setId(rs.getString("project_id"));
			p.setName(rs.getString("projectname"));
			p.setDescribe(rs.getString("describe"));
			p.setCreatetime(rs.getString("projectcreatetime"));
			
			in.setProject(p);
			in.setProject_id(rs.getString("project_id"));
			
			return in;
		}

		
		
		
	}
}
